import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'

const contentTypeForm = 'application/x-www-form-urlencoded'
const contentTypeJson = 'application/json'
const responseTypeJson = 'json'
let loading = false

const instance = axios.create({
  withCredentials: true,
  baseURL: '/api',
  timeout: 10 * 1000
})

instance.interceptors.request.use(
  (config) => {
    if (config.showLoading) {
      loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    return config
  },
  (error) => {
    loading?.close()
    ElMessage.error('请求错误，请检查网络连接')
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    const { showLoading, errorCallback, responseType } = response.config
    if (showLoading && loading) {
      loading.close()
    }
    const responseData = response.data
    if (responseType === 'arraybuffer' || responseType === 'blob') {
      return responseData
    }
    if (response.status === 200) {
      return responseData
    } else if (responseData.code === 401) {
      setTimeout(() => {
        window.ipcRenderer.send('reLogin')
      }, 2000)
      return Promise.reject('登录已过期，请重新登录')
    }
    if (errorCallback) {
      errorCallback(responseData)
    }
    return Promise.reject(responseData.msg || '请求失败')
  },
  (error) => {
    loading?.close()
    ElMessage.error('请求错误，请检查网络连接')
    return Promise.reject(error)
  }
)

const request = (config) => {
  const {
    url,
    dataType = 'json',
    methods = 'get',
    params,
    showLoading = true,
    responseType = responseTypeJson
  } = config
  const token = localStorage.getItem('token')
  let headers = {
    Authorization: `Bearer ${token}`
  }
  if (methods.toLocaleLowerCase() === 'get') {
    return instance.get(url, {
      params: params,
      showLoading: showLoading,
      responseType,
      headers
    })
  }
  let contentType = contentTypeForm
  let formData = new FormData()
  for (let key in params) {
    formData.append(key, params[key] || '')
  }
  if (dataType != null && dataType === 'json') {
    contentType = contentTypeJson
  }
  headers['Content-Type'] = contentType
  return instance.post(url, formData, {
    headers: headers,
    showLoading: showLoading,
    responseType
  })
}

export default request
